<?

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

include_once 'controller.inc.php';
include_once 'event_helper.inc.php';

$name = $_POST['name'];
$description = $_POST['description'];
$location = $_POST['location'];

$event_times = getDateTimesFromRequest($_POST);
$start_time = $event_times[0];
$end_time = $event_times[1];

$db_link = db_connect();

$user = db_getUserByEmail($_COOKIE['user']);

$event = new Event();
$event->setOwner($user->getID());
$event->setName($name);
$event->setDescription($description);
$event->setLocation($location);
$event->setStartTime($start_time);
$event->setEndTime($end_time);

$event_id = db_createEvent($event);

$new_roles = array();

$idx = 1;
foreach ($_POST as $key => $val) {
  if (preg_match('/role(?P<num>\d+?)_name/', $key, $role_num) > 0) {
    $role_num = $role_num['num'];
    $role_name = $_POST[$key];
    $role_user_id = $_POST['role'.$role_num.'_user'];
    
    $valid = TRUE;
    foreach ($new_roles as $added_role) {
      if ($added_role->getName() == $role_name && $added_role->getUserID() == $role_user_id) {
        $valid = FALSE;
      }
    }
    if ($valid && !empty($role_name)) {
      $role = new Role();
      $role->setName($role_name);
      $role->setUser($role_user_id);
      $role->setEvent($event_id);
      $new_roles[$idx++] = $role;
    }
  }
}

foreach ($new_roles as $new_role) {
  db_createRole($new_role);
}

db_disconnect($db_link);

header('Location: dashboard.php?success=Event_created');

?>
